# coding=utf-8
# 调用阿里云专有云NAS存储API得到数据，整理每个目录数据的格式，然后调用send_data_to_api()函数发送数据至后端接口，存入数据库

from aliyunsdkasapi.ASClient import ASClient
from aliyunsdkasapi.AsapiRequest import AsapiRequest
import requests
import datetime
import logging
import json
import re

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s : %(levelname)s : %(message)s',
    filename="/home/ali_cloud_nas_api.log"
)


# 提取当前时间，整理格式后返回当前时间值，用于生成result_txt
def result_txt_time():
    now = datetime.datetime.now()
    now_time = now.strftime("%Y%m%d%H%M")
    return now_time


def get_ali_DescribeFileSystem():
    # 本文提供的API调用样例仅供参考，更多详细API调用方法可参照开发文档中的“快速入门”

    # 创建ASClient连接,timeout设置请求超时时间，cert_file设置证书文件，verify是否验证证书
    client = ASClient("ALIBABA_CLOUD_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "region_id", timeout=1000,
                      cert_file=None,
                      verify=False)
    # 设置身份标识,标识调用来源,无实际作用,可随意设置,必填项
    client.setSdkSource("身份标识@asapi-inc.com")
    # ASAPI的Endpoint地址
    endpoint = "https://ASAPI的Endpoint地址"
    # 创建Request
    request = AsapiRequest("NAS", "2017-06-26", "DescribeFileSystems", endpoint)
    # 设置请求方式
    request.set_method("POST")
    # 授权相关参数

    # 接口业务参数设置

    # 设置Headers
    # 部分接口需要在页面headers列表中填写x-acs-organizationId、x-acs-resourceGroupId等组织，资源组信息

    # 发起请求，并获取返回
    response = client.do_request(request)
    dict_res = json.loads(response)
    # python2:  print(response)
    # return str(response, encoding='utf-8')
    return dict_res


# 使用POST协议将数据发送到对端接口
def send_data_to_api(ip, path, assigned_volume, use_volume, residue_volume):

    # 生产环境
    base_url = "https://地址"

    # request_data格式
    request_data = {
        "ip": ip,
        "path": path,
        "assigned_volume": assigned_volume,
        "use_volume": use_volume,
        "residue_volume": residue_volume
    }

    # 使用POST协议发送数据，并接收返回值
    requests_res = requests.post(
        url=base_url,
        data=json.dumps(request_data)
    )
    requests_res_data = requests_res.json()
    # 记录日志
    logging.info("execute send_data_to_api path: {0} result: {1}".format(path, requests_res_data))
    return requests_res_data


# 接收调用阿里云NAS存储API得到的数据，整理每个目录数据的格式，然后调用send_data_to_api()函数发送数据至后端接口，存入数据库
def handle_data(dict_data):
    lists_dict_data = dict_data['FileSystems']['FileSystem']
    # 生成日志，记录整理后准备发送的数据
    result_txt_name = "/home/ali_nas_log_" + result_txt_time() + ".txt"
    with open(result_txt_name, "w") as log:
        tplt = "{:<10}\t{:<10}\t{:<10}\t{:<10}\t{:<10}"
        log.write(tplt.format('ip', 'path', 'assigned_volume(G)', 'use_volume(G)', 'residue_volume(G)', chr(255)))
        log.write('\n')
        for list_dict_data in lists_dict_data:
            ip = '阿里专有云'
            path = list_dict_data['FileSystemId']

            if list_dict_data['QuotaSize'] < list_dict_data['MeteredSize'] or list_dict_data['QuotaSize'] == 1125899906842624 :
                list_dict_data['QuotaSize'] = list_dict_data['MeteredSize']
            
            if list_dict_data['FileSystemId'] == '1138a49837' :
                list_dict_data['QuotaSize'] = list_dict_data['MeteredSize'] 

            assigned_volume = round(list_dict_data['QuotaSize'] / 1024 / 1024 / 1024, 3)
            use_volume = round(list_dict_data['MeteredSize'] / 1024 / 1024 / 1024, 3)
            residue_volume = int((assigned_volume - use_volume) * 1000) / 1000

            try:
                log.write(tplt.format(ip, path, assigned_volume, use_volume, residue_volume, chr(255)))
                log.write('\n')
                logging.info("execute write path ({0}) successful".format(path))
                send_data_to_api(ip, path, assigned_volume, use_volume, residue_volume)
            except:
                log.write("error\n")
                logging.error("execute write path ({0}) error".format(path))


if __name__ == '__main__':
    # get_ali_DescribeFileSystem()
    ali_dict_data = get_ali_DescribeFileSystem()
    handle_data(ali_dict_data)
